<template src="./template.html"></template>

<script>
import Icon from 'components/icon'
import checkForm from 'mixins/checkform'
import { setItem, getItem, removeItem } from 'common/storage'
import { USER_INFO } from 'store/mutation-types'
/* eslint-disable */
import validator from 'utils/form-validate'
import { userLogin, setUserInfoToCache } from './models'

export default {
  components: {
    Icon
  },
  name: 'Login',
  mixins: [
    checkForm,
  ],
  props: {
    isPoplogin: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isSubmiting: false,
      formName: 'loginForm',
      checked: false,
      pwdType: 'password',
      loginForm: {
        userType: '0',
        username: '',
        password: '',
      },
      loginRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { trigger: 'blur', validator: validator.validateLoginIpt },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { trigger: 'blur', validator: validator.validateLoginIpt },
        ]
      },
    };
  },
  watch: {
    isPoplogin() {
      this.loginForm.username = getItem('userName_remember')
    }
  },
  mounted() {
    this.loginForm.username = getItem('userName_remember')
  },
  methods: {
    async $login() {
      if (this.isSubmiting) { return }
      this.isSubmiting = true
      const params = {
        username: this.loginForm.username,
        // password: rsa.encrypt(this.loginForm.password),
        password: this.loginForm.password,
        userType: 0
        // password: hexMd5(this.loginForm.password)
      };
      if (!this.$checkForm(this.formName)) {
        this.isSubmiting = false
        return false
      }
      if (this.checked) {
        setItem('userName_remember', this.loginForm.username)
      } else {
        removeItem('userName_remember')
      }

      try {
        const userInfo = await userLogin(params)
        this.isSubmiting = false

        setUserInfoToCache(userInfo)
        if (this.isPoplogin === true) {
          this.$store.commit(USER_INFO, userInfo)
          window.location.reload()
        } else {
          window.location.href = './'
        }
      } catch (err) {
        console.log(err)
        this.$message.error(err.message)
        this.isSubmiting = false
      }
    },
  },
};
</script>
